/**
 * @see 该界面是“老师界面”的“查看学生考勤情况”
 */


const formatDate = (timestamp) => {
  const time = new Date(timestamp)
  const hoursDate = time.getHours()
  const minutesDate = time.getMinutes()
  const hours = hoursDate >= 10 ? hoursDate : '0' + hoursDate
  const minutes = minutesDate >= 10 ? minutesDate : '0' + minutesDate
  return hours + ':' + minutes
}

const formatDataAndStyle = (item) => {
  switch (item.attendanceStatus) {
    case 1: // 签到
      item.statusText = '签到'
      item.statusStyle = {
        border: '1rpx solid #2172ED',
        backgroundColor: '#E8F1FF',
        color: '#2172ED'
      }
      break
    case 2: // 位置异常
      item.statusText = '位置异常'
      item.statusStyle = {
        border: '1rpx solid #DB3C3C',
        backgroundColor: '#F9EBEB',
        color: '#DB3C3C'
      }
      break
    case 3: // 迟到
      item.statusText = '迟到'
      item.statusStyle = {
        border: '1rpx solid #DB3C3C',
        backgroundColor: '#F9EBEB',
        color: '#DB3C3C'
      }
      break
    case 4: // 免听
      item.statusText = '免听'
      item.statusStyle = {
        border: '1rpx solid #CCCCCC',
        backgroundColor: '#F9F9F9',
        color: '#CCCCCC'
      }
      break
    case 5: // 缺勤
      item.statusText = '缺勤'
      item.statusStyle = {
        border: '1rpx solid #ff4949',
        backgroundColor: '#F9F9F9',
        color: '#ff4949'
      }
      break
    case 6: // 病假
      item.statusText = '病假'
      item.statusStyle = {
        border: '1rpx solid #CCCCCC',
        backgroundColor: '#F9F9F9',
        color: '#CCCCCC'
      }
      break
    case 7: // 事假
      item.statusText = '事假'
      item.statusStyle = {
        border: '1rpx solid #CCCCCC',
        backgroundColor: '#F9F9F9',
        color: '#CCCCCC'
      }
      break
    case 8: // 早退
      item.statusText = '早退'
      item.statusStyle = {
        border: '1rpx solid #CCCCCC',
        backgroundColor: '#F9F9F9',
        color: '#CCCCCC'
      }
      break
    case 9: // 违纪
      item.statusText = '违纪'
      item.statusStyle = {
        border: '1rpx solid #CCCCCC',
        backgroundColor: '#F9F9F9',
        color: '#CCCCCC'
      }
      break
    default:
      break
  }
}



Page({
  data: {
    attendanceRecordsData: [],
    countNum: '',
    signNum: '',
    statusArray: [ // 考勤状态( 1:签到，2:位置异常， 3：迟到， 4：免听， 5：缺勤， 6：病假，7：事假，8：早退，9：违纪)
      { name: '签到', value: 1 },
      { name: '位置异常', value: 2 },
      { name: '迟到', value: 3 },
      { name: '免听', value: 4 },
      { name: '缺勤', value: 5 },
      { name: '病假', value: 6 },
      { name: '事假', value: 7 },
      { name: '早退', value: 8 },
      { name: '违纪', value: 9 }
    ],
    statusIndex: 0,
    currentItem: {}, // 当前课程的数据，从上个页面传过来
    currentStuItem: {}, // 点击修改某个item的数据
    // statusNum: 0 // 点击状态，状态对应的statusArray第几个出现
    recordArray: [],
    recordIndex: 0,
    switch: false,

    page: 1,
    size: 15,

    appMsg: {
      type: '',
      show: false
    },
    refreshing: false,
    nomore: false
  },
  onLoad (options) {
    try {
      const { item } = options
      this.setData({ currentItem: JSON.parse(item) })
      this.getAttendanceStartup()
    } catch (err) {
      wx.showToast({
        title: '数据异常，请稍后再试',
        icon: 'none',
        duration: 2000
      })
    }
  },
  refreshData () {
    this.setData({
      refreshing: true,
      nomore: false,
      attendanceRecordsData: [],
      page: 1
    })
    this.getAttendanceList()
  },
  loadmore () {
    this.setData({ refreshing: true, page: ++this.data.page })
    this.getAttendanceList()
  },
  clickMsgButton () {
    this.getAttendanceList()
  },
  /**
   * @see 接口-获取课程考勤记录
   */
  getAttendanceStartup () {
    const { courseId, week } = this.data.currentItem
    const request = {
      courseId,
      week
    }
    this.setData({
      appMsg: {
        type: 'loading',
        show: true
      }
    })
    wx.$API['schoolStudy/getAttendanceStartup'](request).then((result) => {
      const { data } = result
      if (data.length) {
        data.forEach(item => {
          item.text = `星期${item.dayTime} 第${item.lesson}节 ${formatDate(item.startTime)}开始考勤`
          item.attendanceValidText = item.attendanceValid === 1 ? true : false
        })
        this.setData({
          recordArray: data,
          appMsg: {
            type: 'loading',
            show: false
          }
        })
        this.getAttendanceList()
      } else {
        this.setData({
          recordArray: data,
          appMsg: {
            type: 'none',
            show: true
          },
        })
      }
    }).catch((error) => {
      console.log(error)
      wx.showToast({
        title: error,
        icon: 'none',
        duration: 2000
      })
    })
  },
  /**
   * @see 接口-获取课程考勤详情
   */
  getAttendanceList () {
    const { recordArray, recordIndex, attendanceRecordsData, page, size } = this.data
    if (!recordArray.length) return
    const request = {
      attendanceId: recordArray[recordIndex].attendanceId,
      page,
      size
    }
    wx.$API['schoolStudy/getAttendance'](request).then((result) => {
      const { data, countNum, signNum } = result
      data.forEach((item) => {
        formatDataAndStyle(item)
        item.time = item.attendanceTime > 0 ? formatDate(item.attendanceTime) : '无 '
      })
      this.setData({
        refreshing: false,
        countNum,
        signNum,
        attendanceRecordsData: attendanceRecordsData.concat(data)
      })
      const currentLeng = attendanceRecordsData.length + size
      if (currentLeng >= countNum) {
        this.setData({ nomore: true })
      }
    }).catch((error) => {
      this.setData({
        refreshing: true,
        appMsg: {
          type: 'err',
          show: true
        },
      })
      console.log(error)
    })
  },
  /**
   * @see 接口-更新考勤状态
   */
  updateAttendanceStatus (attendanceStatus) {
    const { currentStuItem, recordArray, recordIndex } = this.data
    const request = {
      attendanceStatus,
      userId: currentStuItem.userId,
      attendanceId: recordArray[recordIndex].attendanceId
    }
    wx.$API['schoolStudy/updateAttendanceStatus'](request).then((result) => {
      wx.showToast({
        title: result,
        icon: 'success'
      })
      currentStuItem.attendanceStatus = attendanceStatus
      formatDataAndStyle(currentStuItem)
      const arrt = `attendanceRecordsData[${currentStuItem.stuIndex}]`
      this.setData({
        [arrt]: currentStuItem
      })
    }).catch((error) => {
      wx.showToast({
        title: error,
        icon: 'none'
      })
      console.log(error)
    })
  },
  /**
   * @see 接口-更新考勤有效状态（是否有效）
   */
  updateAttendanceVaild (attendanceValid) {
    const { recordArray, recordIndex } = this.data
    if (!recordArray.length) return
    if (attendanceValid) {
      attendanceValid = 1
    } else {
      attendanceValid = 2
    }
    const request = {
      attendanceValid,
      attendanceId: recordArray[recordIndex].attendanceId
    }
    wx.showLoading({ title: '正在处理...', mask: true })
    wx.$API['schoolStudy/updateAttendanceVaild'](request).then((result) => {
      wx.hideLoading()
      wx.showToast({
        title: result,
        icon: 'success'
      })
      const item = recordArray[recordIndex]
      const arrt = `recordArray[${recordIndex}]`
      this.setData({
        [arrt]: {
          ...item,
          attendanceValidText: attendanceValid === 1 ? true : false,
          attendanceValid
        }
      })
    }).catch((error) => {
      wx.showToast({
        title: error,
        icon: 'none'
      })
      console.log(error)
    })
  },
  /**
   * @see 点击周期考勤时间
   */
  bindRecordChange (e) {
    this.setData({
      recordIndex: e.detail.value,
      page: 1
    })
    this.refreshData()
  },
  /**
   * @see 点击按钮修改考勤状态
   */
  clickBtnStatus (e) {
    const { statusArray } = this.data
    const attendanceStatus = statusArray[e.detail.value].value
    this.updateAttendanceStatus(attendanceStatus)
  },
  /**
   * @see 点击按钮记录参数
   */
  clickStatus (e) {
    const { stuItem, stuIndex } = e.currentTarget.dataset
    stuItem.stuIndex = stuIndex
    this.setData({ currentStuItem: stuItem })
  },
  onChange (event) {
    const detail = event.detail
    this.updateAttendanceVaild(detail.value)
  }
})